// 注册
import { creatRegister } from "../../utils/creatRegister";
import textNodeComponents from "../../../sideBarComList/TextNode";
import { Vertices } from '@antv/x6/es/registry/tool/vertices'
export default {
    components: { textNodeComponents },
    data() {
        return {
            adapterNode: null,
        }

    },
    methods: {
        graphEventInit() {
            // 事件注册
            // EVENT: NODE
            this.graph.on("node:click", ({ e, x, y, node, view }) => {
                this.selectCell(view, "node");

            });

            // 显示隐藏连接桩
            this.graph.on("cell:mouseover", () => {
                this.$nextTick(() => {
                    const container = document.getElementById("content");
                    const ports = container.querySelectorAll(".x6-port-body");
                    this.showPorts(ports, true);
                });
            });
            this.graph.on("cell:mouseleave", () => {
                this.$nextTick(() => {
                    const container = document.getElementById("content");
                    const ports = container.querySelectorAll(".x6-port-body");
                    this.showPorts(ports, false);
                });
            });

            this.graph.on("node:added", ({ node, current }) => {
                // if (node.getData().describe) return;
                // let text = node.getData().text || "";
                // let { x, y } = node.position();
                // let { width, height } = node.size();
                // const describeNode = this.graph.createNode({
                //   shape: "text-block",
                //   x: x,
                //   y: y + height + 10,
                //   width: width,
                //   height: 25,
                //   text: text,
                //   attrs: {
                //     body: {
                //       fill: "none",
                //       stroke: "none",
                //       strokeWidth: 1,
                //     },
                //   },
                //   data: {
                //     describe: true,
                //   },
                // });
                // node.addChild(describeNode);
            });
            this.graph.on("node:move", ({ node, options }) => {
                this.$refs.manipulate.init(null);
                this.$emit("handleHeader", null);
                // 清除选中和Transform
                // this.graph.cleanSelection();
                // this.graph.clearTransformWidgets();
            });
            this.graph.on("node:selected", ({ node }) => {
                if (node.getData) {
                    try {
                        let { adapter } = node.getData()
                        if (adapter) {
                            node.addTools([
                                {
                                    name: 'button',
                                    args: {
                                        markup: [
                                            {
                                                tagName: 'rect',
                                                selector: 'button',
                                                attrs: {
                                                    width: 40,
                                                    height: 20,
                                                    rx: 5,
                                                    ry: 5,
                                                    stroke: '#1E90FF',
                                                    'stroke-width': 1,
                                                    fill: 'white',
                                                    cursor: 'pointer',
                                                },
                                            },
                                            {
                                                tagName: 'text',
                                                textContent: '添加边',
                                                selector: 'icon',
                                                attrs: {
                                                    fill: '#1E90FF',
                                                    'font-size': 8,
                                                    'text-anchor': 'middle',
                                                    'pointer-events': 'none',
                                                    y: '1.6em',
                                                    x: '2.5em',
                                                },
                                            },
                                        ],
                                        x: '100%',
                                        y: '100%',
                                        offset: { x: 5, y: -40 },
                                        onClick: ({ cell, view }) => {
                                            cell.removeTools()
                                            this.graph.unselect(cell)
                                            this.graph.clearTransformWidgets()
                                            cell.attr('body/magnet', true)
                                            cell.setData({
                                                currentStyle: {
                                                    stroke: '#1E90FF',
                                                    strokeWidth: 2,
                                                    strokeType: 'dashed',
                                                    cursor: 'crosshair',
                                                }
                                            })
                                            this.adapterNode = cell
                                        },
                                    }
                                }
                            ])
                            node.toFront()
                        }
                    } catch (err) { }
                }
            })
            this.graph.on("node:unselected", ({ node }) => {
                node.removeTools();
            });
            // event:EDGE
            this.graph.on("edge:click", ({ e, x, y, edge, view }) => {
                this.selectCell(view, "edge");
            });
            this.graph.on("edge:selected", ({ edge }) => {
                edge.addTools([
                    {
                        name: "vertices",
                        args: {
                            attrs: {
                                r: 4,
                                fill: "#ffffff",
                                stroke: "#1E90FF",
                                strokeWidth: 3,
                            },
                            modifiers: "ctrl",
                            stopPropagation: false,
                        },
                    },
                    //  {
                    //   name: "source-arrowhead",
                    //   args: {
                    //     attrs: {
                    //       fill: "#000",
                    //       stroke: '#fff',
                    //       'stroke-width': 1,
                    //     },
                    //   },
                    // },
                    {
                        name: "target-arrowhead",
                        args: {
                            attrs: {
                                d: 'M -11 6 L 2.904 0.034 L -11 -6 L -7 0 L -11 6',
                                fill: "#7c68fc",
                                stroke: '#ff4d4f',
                                'stroke-width': 1,
                            },
                        },
                    },
                ]);
                // 选中后修改颜色/虚线
                edge.attr({
                    line: {
                        stroke: "#7C68FC",
                        strokeDasharray: 5,
                    },
                });
            });
            this.graph.on("edge:unselected", ({ edge }) => {
                edge.removeTools();
                // 取消选中后修改颜色
                edge.attr({
                    line: {
                        stroke: "#000000",
                        strokeDasharray: 0,
                    },
                });
            });
            this.graph.on("edge:dblclick", ({ edge, e }) => { });
            // by:https://github.com/antvis/X6/issues/3439
            // this.graph.on("edge:connected", ({ e, edge, view, isNew, currentCell, currentView }) => {
            //   console.log('触发连接事件')
            //   if (isNew) {
            //     try {
            //       const target = edge.getTargetCell()
            //       const source = edge.getSourceCell()
            //       if (target.isNode()) {
            //         let { adapter } = target.getData()
            //         console.log(adapter, 'adapter')
            //         if (adapter) {
            //           edge.attr({
            //             line: {
            //               targetMarker: {
            //                 name: ''
            //               }
            //             }
            //           })
            //           target.toFront()
            //         }
            //       } else if (target.isEdge()) {
            //       }
            //     } catch (err) { }
            //   }
            // });
            this.graph.on("edge:mouseup", ({ e, edge, view }) => {
                let { x, y, currentView } = view.getEventData(e)
                this.resetAdapter()
                if (currentView && x && y) {
                    try {
                        if (currentView.cell.isEdge()) {
                            const length = currentView.getClosestPointLength({ x, y });
                            if (!length) return;
                            edge.setTarget({
                                cell: currentView.cell,
                                anchor: {
                                    name: "length",
                                    args: {
                                        length,
                                    },
                                },
                                attrs: {
                                    line: {
                                        targetMarker: {
                                            name: ''
                                        }
                                    }
                                },
                                connectionPoint: "anchor",
                            });
                            edge.attr({
                                line: {
                                    targetMarker: {
                                        name: ''
                                    }
                                }
                            })
                        } else if (currentView.cell.isNode()) {
                            const target = edge.getTargetCell()
                            let { adapter } = target.getData()
                            if (adapter) {
                                edge.attr({
                                    line: {
                                        targetMarker: {
                                            name: ''
                                        }
                                    }
                                })
                                target.toFront()
                            } else {
                                edge.attr({
                                    line: {
                                        targetMarker: 'classic'
                                    }
                                })
                            }
                        }
                    } catch (err) { }
                }

            });
            // event:BLANK
            this.graph.on("blank:dblclick", ({ e, x, y }) => {
                let textNode = {
                    shape: "TextNode",
                    components: textNodeComponents,
                };
                creatRegister(textNode.shape, textNode.components);
                let node = this.graph.addNode({
                    shape: textNode.shape,
                    x: x - 7,
                    y: y - 15,
                    width: 15,
                    height: 30,
                    data: {
                        isDropEnd: true,
                    },
                });
                this.graph.clearTransformWidgets();
                this.graph.resetSelection(node);
            });
            // 点击空白处重置控制面板
            this.graph.on("blank:mousedown", () => {
                this.$nextTick(() => {
                    this.pickCells = this.graph.getSelectedCells();
                });
                this.$refs.manipulate.init(null);
                this.$emit("handleHeader", null);
                // 清空选中
                this.graph.cleanSelection();
                this.graph.getNodes().forEach((node) => {
                    if (node.shape === "TextNode") {
                        if (node.getData().text.trim() === "") {
                            this.graph.removeNode(node);
                            return;
                        }
                        node.setData({
                            textEditStatus: false,
                        });
                    }
                });
            });
            this.graph.on("blank:click", () => {
                this.resetAdapter()
            });
            // event:OTHER
            this.graph.on("cell:changed", ({ cell, options }) => {
                this.graphChanged();
            });
            this.graph.on("cell:removed", () => {
                this.graphChanged();
            });
            this.graph.on("history:change", () => {
                // 更新历史记录状态
                this.$emit("setStatus", "undo", !this.graph.canUndo());
                this.$emit("setStatus", "redo", !this.graph.canRedo());
            });
            this.graph.on("cell:click", ({ e, x, y, cell, view }) => {
                this.$emit("handleHeader", cell, view, "cell");
            });
            this.graph.on("cell:selected", ({ cell }) => {
                this.selectCell(cell);
            });
        },
        resetAdapter() {
            if (this.adapterNode) {
                this.adapterNode.attr('body/magnet', false)
                this.adapterNode.setData({
                    currentStyle: {
                        stroke: '#000',
                        strokeWidth: 2,
                        strokeType: 'solid',
                        cursor: 'move',

                    }
                })
                this.adapterNode.toFront()
                this.adapterNode = null
            }
        }
    },
}